<template>
  <view class="container">
    <view class="container_header">
      <view slot="right-icon" class="pet_image" @click="getImg(Pet.imgArr,'touxiang')">
        <image v-if="Pet.imgArr.length === 0" src="http://qichong-1256206693-1256206693.cos.ap-nanjing.myqcloud.com/upload/20210617/a1b0aedabc466612a506a75eda513e72.png" mode="aspectFill"></image>
        </image>
        <block v-if="Pet.imgArr.length !== 0" v-for="(item,i) in Pet.imgArr" :key="i">
          <image :src="item.link" mode="aspectFill"></image>
        </block>
      </view>
      <van-field :model:value="Pet.nickname" maxlength="10" placeholder-style="text-align:center" input-align="center"
        placeholder="昵称不得超过十个字符" @input="Blurnickname" />
      <image v-if="Pet.imgArr.length === 0" src="/static/images/mine/update.png" mode="aspectFill" class="minImage">
    </view>

    <!-- 选择门店 -->
    <van-cell :border="false" title="选择门店" :value="shopName.deptName?shopName.deptName:'猫鸭店'" is-link
      @click="navTo('/pages/shop/list')" />

    <van-cell :border="false" title="宠物性别">
      <view class="container_radio">
        <view :class="['container_radio_GG', GenderShow? '' : 'container_radio_active']" @click="RadioGG">
          GG
        </view>
        <view :class="['container_radio_GG', GenderShow? 'container_radio_active' : '']" @click="RadioMM">
          MM
        </view>
      </view>
    </van-cell>

    <van-cell is-link :border="false" title="宠物品种" :value="Pet.varieties" @click="navTo('/subpkg/category/category')">
    </van-cell>

    <van-cell-group :border="false">
      <van-field :border="false" :model:value="Pet.coat" label="宠物毛色" placeholder="请输入毛色" input-align="right"
        @blur="Changecoat"></van-field>
    </van-cell-group>

    <van-cell :border="false" title="绝育情况">
      <view class="container_radio">
        <view :class="['container_radio_GG', CannotShow? '' : 'container_radio_active']" @click="CannotYue">
          是
        </view>
        <view :class="['container_radio_GG', CannotShow? 'container_radio_active' : '']" @click="CannotNo">
          否
        </view>
      </view>
    </van-cell>

    <van-cell :border="false" title="出生日期" is-link :value="Pet.time | dateFormat" @click="Pet_Data" />

    <van-cell :border="false" title="到家日期" is-link :value="Pet.hometime | dateFormat" @click="Home_Pet_Data" />

    <!-- 价格 -->
    <van-cell-group :border="false">
      <van-field :border="false" :model:value="Pet.money" label="起售价" placeholder="例如：¥500" input-align="right"
        @blur="Changemoney"></van-field>
    </van-cell-group>

    <!-- 性格 -->
    <view class="describe">
      <view class="describe_title">
        性格特点
      </view>
      <view class="container_input">
        <textarea class="container_input_box" v-model="Pet.characterValue" maxlength="50"
          placeholder-style="color:rgba(61, 61, 61, 0.5)" placeholder="例如：可爱，善良..." @input="characterInput" />
        <text class="container_input_abso">{{characterList}}/50</text>
        <!-- <image class="minImage" src="/static/picture.png" mode="widthFix"></image> -->
        <!-- <image class="minImage minImage1" src="/static/invite.png" mode="widthFix"></image> -->
      </view>
    </view>

    <!-- 特殊状况 -->
    <view class="describe">
      <view class="describe_title">
        撸宠方式
      </view>
      <view class="container_input">
        <textarea class="container_input_box" v-model="Pet.specialValue" maxlength="50"
          placeholder-style="color:rgba(61, 61, 61, 0.5)" placeholder="例如：随便撸..." @input="specialInput" />
        <text class="container_input_abso">{{specialList}}/50</text>
        <!-- <image class="minImage" src="/static/picture.png" mode="widthFix"></image> -->
        <!-- <image class="minImage minImage1" src="/static/invite.png" mode="widthFix"></image> -->
      </view>
    </view>

    <!-- Ta的生活照 -->
    <view class="describe">
      <view class="describe_title">
        Ta的生活照
      </view>
      <view class="container_image">
        <view v-if="Pet.liveimgArr.length != 0" class="container_image_box" v-for="(item,i) in Pet.liveimgArr" :key="i">
          <image :src="item.link" mode="aspectFill"></image>
          <image class="minImage" src="/static/images/mine/no.png" mode="aspectFill"
            @click="CloseImage(Pet.liveimgArr,i)">
          </image>
        </view>
        <view class="container_image_addbox" @click="getImg(Pet.liveimgArr)">
          <view class="container_image_add">
            <image src="/static/add.png" mode="widthFix"></image>
          </view>
          <text v-if="Pet.liveimgArr.length == 0">添加图片/视频</text>
        </view>
      </view>
    </view>

    <van-cell :border="false" title="宠物叫声">
      <view class="container_radio">
        <view v-if="!Pet.record" class="container_radio_GG container_radio_active" @click="recordShow = true">
          添加
        </view>
        <block v-else>
          <view class="container_radio_update container_radio_active" @click="recordupdate">
            重新录制
          </view>
          <view class="container_radio_GG container_radio_red" @click="recordRemove">
            删除
          </view>
        </block>
      </view>
    </van-cell>

    <view class="record_box" v-if="Pet.record" @click="playRecord">
      <view class="record_box_Item">
        <text>{{sec}} ''</text>
        <image src="/static/sound-recording/playvoice.png" mode="widthFix"></image>
      </view>
    </view>

    <view class="new_pet">
      <button type="success" class="new_pet_button" @click="naw_Petbottom">{{Pet_id?'修改宠物档案':'建立宠物档案'}}</button>
    </view>

    <!-- 时间弹出 -->
    <van-popup :show="Datashow" round position="bottom" custom-style="height: 44%;">
      <van-datetime-picker type="date" :value="currentDate" :max-date="maxDate" @cancel="Pet_CancelData"
        @confirm="Pet_ConfirmData" :formatter="formatter" />
    </van-popup>

    <!-- 时间弹出 -->
    <van-popup :show="HomeDatashow" round position="bottom" custom-style="height: 44%;">
      <van-datetime-picker type="date" :value="currentDate" :max-date="maxDate" @cancel="Home_Pet_CancelData"
        @confirm="Home_Pet_ConfirmData" :formatter="formatter" />
    </van-popup>

    <!-- 录音 -->
    <van-popup :show="recordShow" custom-style="height: 40%;width:70%" round @close="onrecordClose">
      <sound-recording ref="recordItem" @confirm="recordingConfirm"></sound-recording>
    </van-popup>
  </view>
</template>

<script>
  import soundRecording from '@/components/sound-recording/sound-recording.vue'
  import {
    removeFile,
  } from "@/api/user.js";

  import {
    storePethealthItem
  } from "@/api/home.js";

  import {
    newShopchives,
    removelabel
  } from '@/api/new_pet.js'

  import {
    mapGetters,
    mapActions
  } from 'vuex'

  export default {
    data() {
      return {
        Pet: {
          imgArr: [],
          // 生活
          liveimgArr: [],
          nickname: '',
          coat: '',
          // 时间
          time: '2021-01-01',
          hometime: '2021-01-01',
          // 标签数据
          traitLabelItem: [],
          gender: '0',
          // 绝育
          sterilization: '0',
          id: false,
          // 品种
          varieties: '请选择',
          // 金额
          money: '',
          // 性格
          characterValue: '',
          // 互动
          specialValue: '',
          // 录音
          record: ''
        },
        // 门店
        shopName: {},
        // 录音弹框
        recordShow: false,
        // 录音秒数
        sec: 0,
        // 品种id
        varietiesValue: 0,
        // 性格长度
        characterList: 0,
        // 特殊长度
        specialList: 0,
        // 富品种id
        varietiesValueId: 0,
        // updateList: [],
        Datashow: false,
        HomeDatashow: false,
        Pet_id: false,
        // 判断是否添加类名
        GenderShow: false,
        // 判断是否绝育
        CannotShow: false,
        aCxt: false,
        currentDate: new Date().getTime(),
        maxDate: new Date().getTime(),
        formatter(type, value) {
          if (type === 'year') {
            return `${value}年`;
          } else if (type === 'month') {
            return `${value}月`;
          }
          return value;
        },
        // 修改数据
        editdataList: {}
      };
    },
    computed: {
      ...mapGetters('m_user', ['currentStoreId']),
      ...mapGetters('m_pet', ['RecordCategoryId'])
    },
    onLoad(option) {
      // this.Pet_id = option.id
      this.editdataList = uni.getStorageSync('editdata')
      uni.removeStorageSync('editdata')
      if (this.editdataList) {
        // console.log(this.editdataList)
        // 获取回显修改
        this.updateTypeItem(this.editdataList)
      }
      // 获取门店
      this.$eventHub.$on('emit', (data) => {
        this.shopName = data
        // console.log(data)
      });
    },
    filters: {
      //过滤器 用于格式化时间
      dateFormat: function(value) {
        var date = new Date(value); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var year = date.getFullYear();
        var month = ("0" + (date.getMonth() + 1)).slice(-2);
        var sdate = ("0" + date.getDate()).slice(-2);
        // 拼接
        var result = year + "-" + month + "-" + sdate
        // 返回
        return result;
      },
    },
    components: {
      soundRecording
    },
    methods: {
      onrecordClose() {
        this.recordShow = false
      },
      // 录音文件
      recordingConfirm(e) {
        this.Pet.record = e.voicePath
        this.sec = e.sec.toFixed(2)
        // console.log(this.record)
        this.recordShow = false
      },
      // 重新录音
      recordupdate() {
        this.recordShow = true
        this.$refs.recordItem.reset()
      },
      // 播放
      playRecord() {
        this.aCxt = uni.createInnerAudioContext();
        this.aCxt.src = this.Pet.record;
        this.aCxt.play();
      },
      // 删除录音
      recordRemove() {
        this.Pet.record = ''
        this.$refs.recordItem.reset()
      },
      // 回显修改
      updateTypeItem(editdataList) {
        this.Pet.nickname = editdataList.productName
        this.Pet.imgArr = editdataList.previewImage !== '' ? this.imgArrArr(editdataList.previewImage.split(',')) : [],
          // console.log(editdataList.sliderImgs)
        this.Pet.liveimgArr = editdataList.sliderImgs !== '' ? this.imgArrArr(editdataList.sliderImgs) : []
        this.Pet.time = editdataList.birthday
        this.Pet.gender = editdataList.sex
        if (editdataList.sex === '0') {
          this.GenderShow = false
        } else {
          this.GenderShow = true
        }
        this.Pet.hometime = editdataList.arriveHomeDate
        this.Pet.coat = editdataList.coatColor
        this.Pet.sterilization = editdataList.neuter
        if (editdataList.neuter === '0') {
          this.CannotShow = false
        } else {
          this.CannotShow = true
        }
        this.Pet.id = editdataList.id
        this.Pet.varieties = editdataList.category.categoryName
        this.varietiesValue = editdataList.categoryId
        this.varietiesValueId = editdataList.categoryParentId
        this.Pet.money = editdataList.price
        this.Pet.characterValue = editdataList.nature
        this.Pet.specialValue = editdataList.interactive
        this.Pet.record = editdataList.barking
        this.shopName.deptName = editdataList.shopName
        this.shopName.id = editdataList.shopId
      },
      Blurnickname(e) {
        // console.log(e)
        this.Pet.nickname = e.detail
      },
      // 毛色
      Changecoat(e) {
        // console.log(e)
        this.Pet.coat = e.detail.value
      },
      // 价格
      Changemoney(e) {
        // console.log(e)
        this.Pet.money = e.detail.value
      },
      Pet_Data() {
        this.Datashow = true
      },
      Pet_ConfirmData(e) {
        this.Datashow = false
        // console.log(e.detail)
        this.Pet.time = e.detail
      },
      Pet_CancelData() {
        this.Datashow = false
      },
      Home_Pet_Data() {
        this.HomeDatashow = true
      },
      Home_Pet_ConfirmData(e) {
        this.HomeDatashow = false
        // console.log(e.detail)
        this.Pet.hometime = e.detail
      },
      Home_Pet_CancelData() {
        this.HomeDatashow = false
      },
      RadioGG() {
        this.Pet.gender = '0'
        this.GenderShow = false
      },
      RadioMM() {
        this.Pet.gender = '1'
        this.GenderShow = true
      },
      CannotYue() {
        this.Pet.sterilization = '0'
        this.CannotShow = false
      },
      CannotNo() {
        this.Pet.sterilization = '1'
        this.CannotShow = true
      },
      // 性格
      characterInput(e) {
        this.characterList = e.detail.cursor
        this.Pet.characterValue = e.detail.value.trim()
      },
      // 特殊
      specialInput(e) {
        this.specialList = e.detail.cursor
        this.Pet.specialValue = e.detail.value.trim()
      },
      getImg(imageData, type) {
        let self = this;
        self.$util.uploadImageOne('blade-resource/oss/endpoint/put-file', function(res) {
          const data = JSON.parse(res)
          // console.log(data)
          if (imageData.length != 0 && type) {
            let imgInfo = {
              link: data.data.link,
              name: data.data.name
            }
            self.CloseImage(imageData, 0)
            imageData.push(imgInfo)
            return
          }
          // console.log(data)
          imageData.push(data.data)
        });
      },
      CloseImage(data, i) {
        // console.log(event)
        // console.log(this.Pet.imgArr[i].name.substr(7))
        removeFile(data[i].name).then(res => {
          // console.log(res)
          if (res.code !== 200) return uni.showToast({
            title: "删除失败"
          })
          data.splice(i, 1)
          // console.log(data)
        })
      },
      navTo(url) {
        uni.navigateTo({
          url: url
        })
      },
      async naw_Petbottom() {

        if (this.Pet.nickname && this.shopName.id && this.Pet.imgArr.length != 0) {
          const imgArr = []
          this.Pet.imgArr.forEach(item => {
            imgArr.push(item.link)
          })

          const liveimgArr = []
          this.Pet.liveimgArr.forEach(item => {
            liveimgArr.push(item.link)
          })

          if (this.editdataList) {
            // 修改
            const updateuser = {
              previewImage: imgArr.join(','),
              productName: this.Pet.nickname,
              sex: this.Pet.gender,
              birthday: this.$util.formatDateTime(new Date(this.Pet.time)).substr(0, 10),
              arriveHomeDate: this.$util.formatDateTime(new Date(this.Pet.hometime)).substr(0, 10),
              coatColor: this.Pet.coat,
              neuter: this.Pet.sterilization,
              categoryParentId: this.varietiesValueId,
              categoryId: this.varietiesValue,
              categoryName: this.Pet.varieties,
              price: this.Pet.money,
              sliderImgs: liveimgArr.join(','),
              interactive: this.Pet.specialValue,
              nature: this.Pet.characterValue,
              barking: this.Pet.record,
              shopId: this.shopName.id,
              id:this.editdataList.id
            }
            this.AddCategoryList(updateuser)
          } else {
            // 创建
            // console.log(this.Pet.traitLabelItem.join(','))
            if (this.Pet.time <= this.Pet.hometime) {
              const user = {
                previewImage: imgArr.join(','),
                productName: this.Pet.nickname,
                sex: this.Pet.gender,
                birthday: this.$util.formatDateTime(new Date(this.Pet.time)).substr(0, 10),
                arriveHomeDate: this.$util.formatDateTime(new Date(this.Pet.hometime)).substr(0, 10),
                coatColor: this.Pet.coat,
                neuter: this.Pet.sterilization,
                categoryParentId: this.varietiesValueId,
                categoryId: this.varietiesValue,
                categoryName: this.Pet.varieties,
                price: this.Pet.money,
                sliderImgs: liveimgArr.join(','),
                interactive: this.Pet.specialValue,
                nature: this.Pet.characterValue,
                barking: this.Pet.record,
                shopId: this.shopName.id
              }
              // console.log(user)
              this.AddCategoryList(user)
            } else {
              uni.showToast({
                title: '出生日期必须小于到家日期哦 ~',
                icon: 'none'
              })
            }
          }
        } else {
          uni.showToast({
            title: '请填写必填项！',
            icon: 'none'
          })
        }
      },
      // 优化 从后台回显的图片数据
      imgArrArr(num) {
        const img = []
        num.forEach(item => {
          img.push({
            link: item,
            name: item.substr(50)
          })
        })
        return img
      },
      AddCategoryList(user) {
        newShopchives(user).then(res => {
          // console.log(res)
          uni.switchTab({
            url: '/pages/tabbar/me/index'
          })
          this.$util.Tips({
            title: '录入成功!'
          });
        }).catch(err => {
          this.$util.Tips({
            title: err
          });
        })
      }
    }
  }
</script>

<style lang="scss">
  /deep/ .van-picker {
    padding: 24rpx;
    font-size: 36rpx;

    .van-picker__cancel,
    .van-picker__confirm {
      color: rgba(61, 61, 61, 1);
      font-size: 34rpx;
    }

    .van-ellipsis {
      font-size: 32rpx;
    }
  }

  /deep/ .van-cell {
    padding-top: 35rpx !important;
    padding-bottom: 35rpx !important;
    align-items: center;
    width: 100% !important;

    .van-cell__title {
      font-size: 28rpx !important;
      line-height: 64rpx;
    }
  }

  /deep/ .van-popup {
    overflow: hidden;
  }

  /deep/ .Text {
    color: #000000;
    font-size: 30rpx;
  }

  .container {
    padding-bottom: 140rpx;

    .container_header {
      position: relative;
      padding-top: 46rpx;
      width: 100%;
      height: 331rpx;
      // background-color: #f9f9f9;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .pet_image {
        position: relative;
        width: 170rpx;
        height: 170rpx;
        // margin-bottom: 10rpx;
        // overflow: hidden;
        display: flex;
        justify-content: center;

        image {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      .minImage {
        position: absolute;
        bottom: 127rpx;
        // left: 0;
        width: 38rpx;
        height: 38rpx;
      }
    }

    .container_radio {
      display: flex;
      justify-content: flex-end;

      .container_radio_GG {
        width: 100rpx;
        height: 54rpx;
        background-color: rgba(61, 61, 61, 0.1);
        border-radius: 211rpx;
        text-align: center;
        line-height: 54rpx;
        margin-left: 22rpx;
        color: rgba(61, 61, 61, 0.5);
        font-size: 30rpx;
      }

      .container_radio_update {
        width: 172rpx;
        height: 54rpx;
        background-color: rgba(61, 61, 61, 0.1);
        border-radius: 211rpx;
        text-align: center;
        line-height: 54rpx;
        // margin-left: 22rpx;
        color: rgba(61, 61, 61, 0.5);
        font-size: 30rpx;
      }

      .container_radio_active {
        color: #000;
        background-color: rgba(253, 211, 56, 1);
      }

      .container_radio_red {
        color: #fff;
        background-color: rgba(255, 87, 51, 1);
      }


    }

    .new_pet {
      position: fixed;
      z-index: 99;
      bottom: 0;
      padding: 24rpx;
      width: 750rpx;
      height: 128rpx;
      box-sizing: border-box;
      background-color: #fff;

      .new_pet_button {
        // width: 702rpx;
        height: 82rpx;
        background-color: #FDD338;
        border-radius: 6px;
        color: rgba(61, 61, 61, 1);
        line-height: 82rpx;
        border-radius: 82rpx;
        font-size: 16px;
        font-weight: 500;
      }
    }

    .describe {
      padding: 35rpx 32rpx;

      .describe_title {
        color: rgba(61, 61, 61, 1);
      }

      .container_input {
        position: relative;
        // width: 704rpx;
        height: 268rpx;
        background-color: rgba(247, 247, 247, 1);
        border-radius: 10rpx;
        margin-top: 28rpx;
        padding: 29rpx 36rpx;
        box-sizing: border-box;
        font-size: 26rpx;


        .container_input_box {
          height: 260rpx !important;
        }

        .container_input_abso {
          position: absolute;
          bottom: 30rpx;
          right: 50rpx;
          color: rgba(61, 61, 61, 0.5);
        }

        .minImage {
          position: absolute;
          bottom: 30rpx;
          left: 50rpx;
          width: 40rpx;
          height: 36rpx;
        }

        .minImage1 {
          left: 150rpx;
        }
      }

      .container_image {
        display: flex;
        flex-wrap: wrap;
        align-items: center;

        .container_image_box:nth-child(4n) {
          margin-right: 0rpx;
        }

        .container_image_box {
          position: relative;
          width: 157rpx;
          height: 157rpx;
          margin-top: 40rpx;
          border-radius: 10rpx;
          // margin-bottom: 20rpx;
          // overflow: hidden;
          margin-right: 20rpx;
          background-color: #007AFF;
          // box-sizing: border-box;


          image {
            width: 100%;
            height: 100%;
            border-radius: 10rpx;
          }

          .minImage {
            position: absolute;
            top: -10rpx;
            right: -10rpx;
            width: 40rpx;
            height: 40rpx;
            border-radius: 50%;
          }
        }

        .container_image_addbox {
          margin-top: 40rpx;
          display: flex;
          align-items: center;

          text {
            color: rgba(61, 61, 61, 0.5);
            font-size: 28rpx;
            margin-left: 37rpx;
          }
        }

        .container_image_add {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 160rpx;
          height: 160rpx;
          background-color: rgba(245, 245, 245, 1);
          border-radius: 10rpx;

          image {
            width: 40rpx;
            height: 40rpx;
          }
        }
      }
    }

    .record_box {
      padding: 0rpx 32rpx;

      .record_box_Item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        // width: 654rpx;
        height: 84rpx;
        background-color: rgba(245, 245, 245, 1);
        border-radius: 211rpx;
        padding: 0 40rpx;

        image {
          width: 37rpx;
        }

        text {
          color: rgba(0, 0, 0, 0.7);
          font-size: 34rpx;
        }
      }
    }
  }
</style>
